package com.janwen.spring.trx.declarative;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("trxAddService")
public class TrxAddService extends TrxBaseService {
	@Autowired
	private TrxNestedService nestedService;

	public void addStuff(String name, int age) throws Exception {

		super.recoverData();
		String sql = "INSERT INTO stuff SET name=?,age=?";
		super.getJdbcTemplate().update(sql, name, age);
		/*
		 * 同一个bean其它方法使用当前方法相同事务
		 * updateAge方法抛出exception,updateAge方法内部做catch,整个事务提交,
		 */
	//	updateAge(name, age + 200);
		
		/**
		 * 抛出exception不是runtimeexception,throw Exception默认不回滚
		 * try catch后事务正常都正常提交,不try catch整个事务回滚
		 */
		try {
			updateAge(name);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public void nestedAddTrx(String name, int age) {
		String sql = "INSERT INTO stuff SET name=?,age=?";
		super.getJdbcTemplate().update(sql, name, age);
		updateAge(name);
	}

	public void deleteStuff(String name) {
		int age_update = nestedService.queryAge(name);
		nestedService.deleteStuff(name, age_update);
	}

	public void updateAge(String name) {
		String sql = "UPDATE stuff sf SET sf.name=?,sf.age=? WHERE sf.name=?";
		getJdbcTemplate().update(sql, name, 100, name);
		//非RuntimeException事务不回滚
		//throw new Exception("exception @updateAge()");
		throw new RuntimeException("runtime exception @updateAge()");
	}

	public void updateAge(String name, int age) {
		try {
			String sql = "UPDATE stuff sf SET sf.name=?,sf.age=? WHERE sf.name=?";
			getJdbcTemplate().update(sql, name, age + 10, name);
			throw new RuntimeException("runtime exception @updateAge()");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
